﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Adp.Core.Attribute;
using Adp;
using Adp.Common;
using Yqd.Enm;
using Yqd.Models;

namespace Yqd.Core
{
    public class SuperviseService
    {
        public static void UpdateDelayStatus()
        {
            using (var ctx = Fn.GetService<YqdContext>())
            {
                Logs.Warning<SuperviseService>("督导督查协调滞后状态开始更新！");
                var nt = DateTime.Now.Date;
                var sIDs = new List<int>();
                var cIDs = new List<int>();
                var eIDs = new List<int>();
                var pIDs = new List<int>();
                var assign = ctx.Yqd_Assign.Where(it => it.AssignLimit < nt);
                sIDs.AddRange(assign.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).ToArray());
                cIDs.AddRange(assign.Where(it => it.ItemType == 事项类型.申请协调).Select(it => it.ItemID).ToArray());
                eIDs.AddRange(assign.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).ToArray());
                pIDs.AddRange(assign.Where(it => it.ItemType == 事项类型.专项督查).Select(it => it.ItemID).ToArray());
                var plan = ctx.Yqd_JobPlan.Where(it => it.PlanCompleteTime != null && it.PlanCompleteTime < nt && it.CheckStatus == 审核状态.同意);
                sIDs.AddRange(plan.Where(it => it.ItemType == 事项类型.钉办督导).Select(it => it.ItemID).ToArray());
                cIDs.AddRange(plan.Where(it => it.ItemType == 事项类型.申请协调).Select(it => it.ItemID).ToArray());
                eIDs.AddRange(plan.Where(it => it.ItemType == 事项类型.精准督查).Select(it => it.ItemID).ToArray());
                pIDs.AddRange(plan.Where(it => it.ItemType == 事项类型.专项督查).Select(it => it.ItemID).ToArray());
                var sql = "";
                if (sIDs.Count() > 0)
                {
                    sql += "update Yqd_Supervise set Status={1} where (Status={2} or Status={3}) and  SuperviseID in({0});";
                }
                if (cIDs.Count() > 0)
                {
                    sql += "update Yqd_Coordinate set Status={1} where (Status={2} or Status={3}) and  CoordinateID in({4});";
                }
                if (eIDs.Count() > 0)
                {
                    sql += "update Yqd_ExactSupervise set Status={1} where (Status={2} or Status={3}) and  SuperviseID in({5});";
                }
                if (pIDs.Count() > 0)
                {
                    sql += "update Yqd_SpecialSupervise set Status={1} where (Status={2} or Status={3}) and  SuperviseID in({5});";
                }
                var ret = 0;
                if (sql != "")
                {
                    sql = string.Format(sql, string.Join(',', sIDs), (int)办理情况.已滞后, (int)办理情况.未回复, (int)办理情况.已回复, string.Join(',', cIDs), string.Join(',', eIDs));
                    ret = ctx.Database.ExecuteSql(sql);
                }
                Logs.Warning<SuperviseService>("督导督查协调滞后状态更新完成！本次更新" + ret + "条。");
            }
        }

        /// <summary>
        /// 获取办理事项
        /// </summary>
        public static (string TableName, string KeyName, bool IsDeal) GetTableName(事项类型 ItemType)
        {
            string tblname = "", keyname = "";
            var IsDeal = false;
            switch (ItemType)
            {
                case 事项类型.钉办督导:
                    tblname = "Supervise";
                    keyname = tblname;
                    break;
                case 事项类型.申请协调:
                    tblname = "Coordinate";
                    keyname = tblname;
                    break;
                case 事项类型.精准督查:
                    tblname = "ExactSupervise";
                    keyname = "Supervise";
                    IsDeal = true;
                    break;
                case 事项类型.专项督查:
                    tblname = "SpecialSupervise";
                    keyname = "Supervise";
                    IsDeal = true;
                    break;
            }
            return (tblname, keyname, IsDeal);
        }

        /// <summary>
        /// 更新督查完成状态
        /// </summary>
        public static int UpdateComplete(int ItemID, 事项类型 ItemType)
        {
            var ctx = Fn.GetService<YqdContext>();
            var ret = 0;
            var complete = true;
            var assign = ctx.Yqd_Assign.Where(it => it.ItemID == ItemID && it.ItemType == ItemType);
            if (!assign.Any()) return ret;
            var plans = ctx.Yqd_JobPlan.Where(it => it.ItemID == ItemID && it.ItemType == ItemType).Select(it => new { it.AssignID, it.CheckStatus, it.IsComplete }).ToList();
            foreach (var a in assign)
            {
                if (!plans.Any(it => it.AssignID == a.AssignID))
                {
                    complete = false;
                    break;
                }
            }
            if (complete)
            {
                if (plans.Any(it => it.CheckStatus != 审核状态.同意))
                {
                    complete = false;
                }
            }
            if (complete)
            {
                if (plans.Any(it => it.CheckStatus == 审核状态.同意 && !it.IsComplete))
                {
                    complete = false;
                }
            }
            if (complete)
            {
                var (tblname, keyname, IsDeal) = GetTableName(ItemType);
                ret = ctx.Database.ExecuteSql("Update Yqd_" + tblname + " set Status={1}" + (IsDeal ? ",IsDeal=0" : "") + " Where " + keyname + "ID={0}", ItemID, (int)办理情况.已完结);
            }
            return ret;
        }

        /// <summary>
        /// 获取督查单号
        /// </summary>
        public static string GetSuperviseNo(long TaskID)
        {
            var ctx = Fn.GetService<YqdContext>();
            var s = ctx.Yqd_SuperviseNo.FirstOrDefault(it => it.TaskID == TaskID);
            if (s != null) return s.SNo;
            var sno = DateTime.Now.Year.ToString();
            var rs = ctx.Yqd_SuperviseNo.Where(it => it.SNo.Substring(0, 4) == sno).OrderByDescending(it => it.ID);
            if (!rs.Any()) sno += "001";
            else sno += (int.Parse(rs.First().SNo.Substring(4)) + 1).ToString("000");
            ctx.Yqd_SuperviseNo.Add(new Yqd_SuperviseNo
            {
                TaskID = TaskID,
                SNo = sno,
                Instime = DateTime.Now
            });
            ctx.SaveChanges();
            return sno;
        }
    }
}